package com.clint.controller;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.clint.model.User;
import org.springframework.web.bind.annotation.*;

/**
 *
 * @author clint dong
 * @version 1.0.0
 *
 */
@RestController
@RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下，可去除
public class UserController {
    //这儿的collections是java中集合的工具类，这边是用来实现同步的，避免数据的脏读
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
    static List<User> usersList = Collections.synchronizedList(new ArrayList<User>());

    @RequestMapping(value="/", method=RequestMethod.GET)
    public List<User> getUserList() {
        User user1 = new User(1L, "clintdong", 11);
        User user2 = new User(2L, "clintzhang", 11);
        User user3 = new User(3L, "clintwang", 11);
        usersList.add(user1);
        usersList.add(user2);
        usersList.add(user3);
        // 处理"/users/"的GET请求，用来获取用户列表
        // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
        List<User> r = usersList;
        return r;
    }

    @RequestMapping(value="/", method=RequestMethod.POST)
    public String postUser(@ModelAttribute User user) {
        // 处理"/users/"的POST请求，用来创建User
        // 除了@ModelAttribute绑定参数之外，还可以通过@RequestParam从页面中传递参数
        users.put(user.getId(), user);
        return "success";
    }

    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        // 处理"/users/{id}"的GET请求，用来获取url中id值的User信息
        // url中的id可通过@PathVariable绑定到函数的参数中
        return usersList.get(1);
    }

    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @ModelAttribute User user) {
        // 处理"/users/{id}"的PUT请求，用来更新User信息
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @ResponseBody
    @RequestMapping(value="/json", method=RequestMethod.GET)
    public String json() {
        User user1 = new User(1L, "clintdong", 11);
        User user2 = new User(2L, "clintzhang", 11);
        User user3 = new User(3L, "clintwang", 11);
        usersList.add(user1);
        usersList.add(user2);
        usersList.add(user3);
        return JSON.toJSONString(usersList);
    }

    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        // 处理"/users/{id}"的DELETE请求，用来删除User
        users.remove(id);
        return "success";
    }
}
